const url = "https://www.ifeng.com/"

const puppeteer=require('puppeteer')


const sleep = time => new Promise(resolve => {
    setTimeout(resolve, time);
}) 

//自运行函数
;(async ()=>{
    console.log("开始")

     //声明一个browser相当于浏览器
     const browser = await puppeteer.launch({
        args: ['--no-sandbox'],
        dumpio: false
    })

    const page = await browser.newPage()  //开启一个新页面
    await page.goto(url, {
        waitUntil: 'networkidle2'  //当这个网页空闲的时候
    })

    await sleep(3000)  //等待三秒


    const result = await page.evaluate(() => {
        var items=document.querySelectorAll('#newsList li a') //NodeList
         
        var itemAry = []; //NodeList转化为数组
        for(var i=0, len = items.length; i < len; i++){     
            itemAry.push(items[i]);    
        } 

        var links = []

        if (itemAry.length >= 1) {

            for (let index = 0; index < itemAry.length; index++) {
                const title = itemAry[index].innerHTML;
                const hreflink = itemAry[index].href;
                links.push({
                    title,
                    hreflink
                })
            }
 
        }

        return links
 
    })
    
    browser.close()
    process.send({ result })
    process.exit(0)

})()